import binascii
import os
import time

from django.contrib.auth import get_user_model
from django.db import models

from social.utils.models import BaseModel

User = get_user_model()


class Token(BaseModel):
    EXPIRE_DURATION = 24 * 60 * 60 * 30 * 3  # 三个月
    MIN_EXPIRE_RENEW = 24 * 60 * 60 * 30
    MIN_ACCESS_UPDATE_DURATION = 60 * 5  # 5分钟更新一次access_at

    key = models.CharField(max_length=40, unique=True)
    user = models.OneToOneField(User, related_name='token', on_delete=models.CASCADE, primary_key=True)
    expire_at = models.IntegerField(default=0)  # 0 为长期有效
    access_at = models.IntegerField(default=0)  # timestamp

    # os = models.CharField(max_length=10, default='')

    def update_token(self):
        self.key = self.generate_key()
        self.expire_at = int(time.time()) + self.EXPIRE_DURATION
        self.save(update_fields=['key', 'expire_at'])

    def save(self, **kwargs):
        if not self.key:
            self.key = self.generate_key()
            self.expire_at = int(time.time()) + self.EXPIRE_DURATION
        return super(Token, self).save(**kwargs)

    def generate_key(self):
        return binascii.hexlify(os.urandom(20)).decode()
